package com.cjj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjj.common.convention.exception.ClientException;
import com.cjj.common.enums.CommentStatus;
import com.cjj.common.enums.PostStatus;
import com.cjj.dao.entity.ForumPost;
import com.cjj.dao.entity.PostComment;
import com.cjj.dao.entity.User;
import com.cjj.dao.mapper.ForumPostMapper;
import com.cjj.dao.mapper.PostCommentMapper;
import com.cjj.dto.req.CommentCreateReqDTO;
import com.cjj.dto.resp.CommentVO;
import com.cjj.service.CommentLikeService;
import com.cjj.service.PostCommentService;
import com.cjj.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PostCommentServiceImpl extends ServiceImpl<PostCommentMapper, PostComment> implements PostCommentService {

    private final PostCommentMapper postCommentMapper;
    private final ForumPostMapper forumPostMapper;
    private final UserService userService;
    private final CommentLikeService commentLikeService;

    /**
     * 创建评论
     */
    @Transactional(rollbackFor = Exception.class)
    public void createComment(CommentCreateReqDTO request) {
        // 验证帖子是否存在且已发布
        ForumPost post = forumPostMapper.selectById(request.getPostId());
        if (post == null || !PostStatus.PUBLISHED.getValue().equals(post.getStatus())) {
            throw new ClientException("帖子不存在或未发布");
        }

        // 如果是回复评论，验证父评论是否存在
        if (request.getParentId() != null && request.getParentId() > 0) {
            PostComment parentComment = postCommentMapper.selectById(request.getParentId());
            if (parentComment == null || !CommentStatus.PUBLISHED.getValue().equals(parentComment.getStatus())) {
                throw new ClientException("父评论不存在或已删除");
            }
        }

        // 创建评论
        PostComment comment = new PostComment()
                .setPostId(request.getPostId())
                .setUserId(request.getUserId())
                .setParentId(request.getParentId() != null ? request.getParentId() : 0L)
                //.setReplyToUserId(request.getReplyToUserId())
                .setContent(request.getContent())
                .setLikeCount(0)
                .setStatus(CommentStatus.PUBLISHED.getValue());

        postCommentMapper.insert(comment);

        // 更新帖子评论数
        updatePostCommentCount(request.getPostId(), 1);
    }

    /**
     * 获取帖子的评论列表（树形结构）
     */
    public List<CommentVO> getPostComments(Long postId, Long currentUserId) {
        // 获取所有评论（一级和二级）
        List<PostComment> allComments = postCommentMapper.selectList(
                Wrappers.lambdaQuery(PostComment.class)
                        .eq(PostComment::getPostId, postId)
                        .eq(PostComment::getStatus, CommentStatus.PUBLISHED.getValue())
                        .orderByAsc(PostComment::getCreateTime)
        );

        // 构建树形结构
        List<CommentVO> result = buildCommentTree(allComments, currentUserId);
        return result;
    }

    /**
     * 构建评论树形结构
     */
    private List<CommentVO> buildCommentTree(List<PostComment> comments, Long currentUserId) {
        // 分组：一级评论和二级评论
        Map<Long, List<PostComment>> replyMap = comments.stream()
                .filter(comment -> comment.getParentId() > 0)
                .collect(Collectors.groupingBy(PostComment::getParentId));

        List<Long> commentIds = comments.stream()
                .map(PostComment::getCommentId)
                .collect(Collectors.toList());

        // 批量查询点赞状态
        Map<Long, Boolean> likeStatusMap = currentUserId != null ?
                commentLikeService.batchCheckLikeStatus(commentIds, currentUserId) : new HashMap<>();

        // 构建一级评论
        return comments.stream()
                .filter(comment -> comment.getParentId() == 0)
                .map(comment -> convertToVO(comment, replyMap.get(comment.getCommentId()), likeStatusMap, currentUserId))
                .collect(Collectors.toList());
    }

    /**
     * 删除评论（软删除）
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteComment(Long commentId, Long userId) {
        PostComment comment = postCommentMapper.selectById(commentId);
        if (comment == null) {
            throw new ClientException("评论不存在");
        }

        // 权限校验：只能删除自己的评论
        if (!comment.getUserId().equals(userId)) {
            throw new ClientException("无权删除他人评论");
        }

        // 软删除
        comment.setStatus(CommentStatus.DELETED.getValue());
        postCommentMapper.updateById(comment);

        // 更新帖子评论数
        updatePostCommentCount(comment.getPostId(), -1);
    }

    /**
     * 更新帖子评论数
     */
    private void updatePostCommentCount(Long postId, int delta) {
        LambdaUpdateWrapper<ForumPost> updateWrapper = Wrappers.lambdaUpdate(ForumPost.class)
                .eq(ForumPost::getPostId, postId)
                .setSql("comment_count = comment_count + " + delta);
        forumPostMapper.update(null, updateWrapper);
    }

    /**
     * 转换为VO
     */
    private CommentVO convertToVO(PostComment comment, List<PostComment> replies,
                                  Map<Long, Boolean> likeStatusMap, Long currentUserId) {
        CommentVO vo = new CommentVO();
        BeanUtil.copyProperties(comment, vo);

        // 设置用户信息
        User user = userService.getById(comment.getUserId());
        if (user != null) {
            vo.setUserName(user.getName());
            vo.setUserAvatar(user.getAvatar());
        }

        // 设置回复目标用户信息
        if (comment.getReplyToUserId() != null) {
            User replyToUser = userService.getById(comment.getReplyToUserId());
            if (replyToUser != null) {
                vo.setReplyToUserName(replyToUser.getName());
            }
        }

        // 设置点赞状态
        vo.setHasLiked(likeStatusMap.getOrDefault(comment.getCommentId(), false));

        // 递归构建回复列表
        if (replies != null && !replies.isEmpty()) {
            List<CommentVO> replyVOs = replies.stream()
                    .map(reply -> convertToVO(reply, null, likeStatusMap, currentUserId))
                    .collect(Collectors.toList());
            vo.setReplies(replyVOs);
        }

        return vo;
    }
}
